package com.coderforum.community.provider;

import com.alibaba.fastjson.JSON;
import com.coderforum.community.dto.AccessTokenDTO;
import com.coderforum.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: xuehai.XUE
 * @MailBox: xuehai.xue@qq.com
 * @Date: 2021/4/1 20:54
 * @Description:
 */
@Component
public class GiteeProvider {
    /** 通过okhttp向gitee认证服务器发送code以获取返回的AccessToken
     *
     * @param accessTokenDTO 传入的待获取认证DTO，包含应用id、密钥、重定向地址等
     * @return AccessToken
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();


            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
            Request request = new Request.Builder()
                    .url("https://gitee.com/oauth/token?grant_type=authorization_code&" +
                            "code=" + accessTokenDTO.getCode() + "&" +
                            "client_id=" + accessTokenDTO.getClient_id() + "&" +
                            "redirect_uri=" + accessTokenDTO.getRedirect_uri() + "&" +
                            "client_secret=" + accessTokenDTO.getClient_secret())
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                String accessToken = string.split("\"")[3];
                return accessToken;
            } catch (IOException e) {
                e.printStackTrace();
            }

        return null;
    }

    /** 应用通过 access_token 访问 Open API 使用用户数据。
     *
     * @param accessToken 传入的accessToken用于向Gitee服务器请求用户数据
     * @return 返回一个giteeUser的具体对象
     */
    public GiteeUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            //将String的json对象自动的解析成GiteeUser类的对象
            GiteeUser giteeUser = JSON.parseObject(string, GiteeUser.class);
            return giteeUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
